<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :page.sync="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      :upload-exceed="uploadExceed"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      :upload-after="uploadAfter"
      :upload-before="uploadBefore"
      :upload-error="uploadError"
      :upload-change="$uploadChange"
      @on-load="getList"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @search-reset="searchReset"
      @size-change="sizeChange"
      @current-change="currentChange"
      @row-update="handleUpdate"
      @row-save="handleSave"
    >
      <template #jumpFlagForm="{ disabled }">
        <el-radio-group
          v-model="form.jumpFlag"
          :disabled="disabled"
          @change="jumpFlagChange"
        >
          <el-radio label="1">不跳转</el-radio>
          <el-radio label="0">跳转</el-radio>
        </el-radio-group>
        <span
          v-if="form.jumpFlag === '0'"
          style="margin-left: 10px; color: #409eff"
          @click="choseLink"
        >
          选择链接
        </span>
        <span
          v-if="btnType !== 'view'"
          style="margin-left: 20px; color: green"
          @click="rulesView"
        >
          如何配置跳转，点击可查看使用说明
        </span>
      </template>
      <template
        slot="menu"
        slot-scope="scope"
      >
        <el-button
          v-if="scope.row.status === ADVERTISING_STATUS.NOT_OPEN"
          type="text"
          size="small"
          @click="
            updateAdvertisingStatus(scope.row, ADVERTISING_IS_DISABLED.ENABLE)
          "
        >
          启用
        </el-button>
        <el-button
          v-if="
            [
              ADVERTISING_STATUS.NOT_STARTED,
              ADVERTISING_STATUS.UNDERWAY,
              ADVERTISING_STATUS.FINISHED,
            ].includes(scope.row.status)
          "
          type="text"
          size="small"
          @click="
            updateAdvertisingStatus(
              scope.row,
              ADVERTISING_IS_DISABLED.FORBIDDEN
            )
          "
        >
          禁用
        </el-button>
      </template>
    </avue-crud>
    <!-- :chose-link-object="form"
      :link-object="form" -->
    <chose-link
      v-model="linkVisible"
      :index-form="form"
      :btn-type="btnType"
      :count="count"
      @success="success"
    ></chose-link>
    <rules-view-dialog v-model="rulesVisible"></rules-view-dialog>
  </basic-container>
</template>

<script>
// const NO_LINK = '2'; // 无链接类型
import {
  fetchList,
  getObj,
  updateAdvertisingStatus,
  addObj,
  putObj,
} from '@/api/operation/advertising';
import { tableOption } from '@/const/crud/advertising/list';
import { mapGetters } from 'vuex';
import crudMixins from '@/mixins/crud';
import choseLink from '../components/choseLink.vue';
import {
  ADVERTISING_STATUS,
  ADVERTISING_IS_DISABLED,
  ADVERTISING_TYPE,
  ADVERTISING_POSITION,
} from '@/const/type';
import RulesViewDialog from '../components/rulesViewDialog.vue';
export default {
  name: 'advertisingList',
  components: {
    choseLink,
    RulesViewDialog,
  },
  mixins: [crudMixins],
  data() {
    return {
      form: {},
      id: null,
      rulesVisible: false,
      tableOption: tableOption(),
      btnType: '',
      linkVisible: false,
      commentVisible: false,
      ADVERTISING_STATUS,
      ADVERTISING_IS_DISABLED,
      appParams: '',
      mpParams: '',
      pageObj: {},
      count: 0,
    };
  },
  computed: {
    ...mapGetters(['permissions']),
  },
  watch: {
    //
    'form.advertisType': {
      deep: true,
      handler(val) {
        console.log('advertisTypeVal', val);
        if (val) {
          const advertisType = this.findObject(
            this.tableOption.column,
            'imageAddressHome'
          );
          if (val === ADVERTISING_TYPE.HOME) {
            advertisType.tip =
              '图片格式支持：jpg/png/jpeg/gif。图片大小支持：最大可上传10M。 图片尺寸推荐： 343 * 120px';
          } else if (val === ADVERTISING_TYPE.BULLET) {
            advertisType.tip =
              '图片格式支持：jpg/png/jpeg/gif。图片大小支持：最大可上传10M。 图片尺寸推荐： 303*366px';
          }
        }
      },
    },
  },
  methods: {
    rulesView() {
      this.rulesVisible = true;
    },
    async uploadAfter(file, done, loading, column) {
      this.$refs.crud.clearValidate('imageAddressHome');
      this.$refs.crud.clearValidate('imageAddressGuide');
      done();
    },
    jumpFlagChange(val) {},
    async uploadBefore(file, done, loading, column) {
      const fileTypeList = [
        'image/png',
        'image/jpg',
        'image/jpeg',
        'image/gif',
      ];
      if (column.prop === 'imageAddressHome') {
        const isType =
          file.type === 'image/png' ||
          file.type === 'image/jpg' ||
          file.type === 'image/jpeg' ||
          file.type === 'image/gif';
        if (!isType) {
          loading();
          this.$message.error('仅支持上传JPG、PNG、JPEG、GIF格式图片!');
          return;
        }
        done();
      } else {
        const isType =
          file.type === 'image/png' ||
          file.type === 'image/jpg' ||
          file.type === 'image/jpeg' ||
          file.type === 'image/gif' ||
          file.type === 'video/mp4';
        if (!isType) {
          loading();
          this.$message.error(
            '仅支持上传JPG、PNG、JPEG、GIF格式图片、MP4视频!'
          );
          return;
        }
        if (file.size > 10 * 1024 * 1024 && fileTypeList.includes(file.type)) {
          loading();
          this.$message.warning(`文件大小不能超过10M`);
          return;
        }
        done();
      }
    },
    success(appCode, mpCode, choseForm) {
      this.appParams = appCode;
      this.mpParams = mpCode;
      this.form = Object.assign({}, this.form, choseForm); // todo
      this.form.appParams = this.appParams;
      this.form.mpParams = this.mpParams;
      // this.linkObject = form;
      // this.lianjieForm = form; // 保存一份数据
    },
    choseLink() {
      this.linkVisible = true;
      this.count += 1;
    },
    //文件大小
    uploadError(error, column) {
      if (error === '文件太大不符合') {
        this.$message.warning(`文件大小不能超过${column.fileSize / 1024}M`);
      }
    },
    uploadExceed(limit, files, fileList, column) {
      console.log(limit, files, fileList, column);
      this.$message.error(`只能上传${limit}个文件`);
    },
    updateAdvertisingStatus(row, disableFlag) {
      const tip =
        disableFlag === ADVERTISING_IS_DISABLED.ENABLE ? '开启' : '禁用';
      this.$confirm(`【是否确认${tip}该广告】`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        await updateAdvertisingStatus({
          id: row.id,
          disableFlag,
        });
        this.$message.success(`${tip}成功`);
        this.getList(this.page, true);
      });
    },
    async getImgWidthHeight(url) {
      return new Promise(function (resolve, reject) {
        const image = new Image();
        image.onload = () => {
          resolve({ width: image.width, height: image.height });
        };
        image.onerror = () => {
          reject(new Error('error'));
        };
        image.src = url;
      });
    },
    async getParams(row) {
      const params = { ...row };
      params.advertisStartDate = row.advertisingFormTime[0];
      params.advertisEndDate = row.advertisingFormTime[1];
      //引导页
      if (params.advertisType === ADVERTISING_TYPE.GUIDE) {
        params.imageAddress = JSON.stringify([
          { fileName: '', url: params.imageAddressGuide },
        ]);
        params.advertisSeat = '';
        params.inforMationFlowSeat = '';
      } else if (params.advertisType === ADVERTISING_TYPE.HOME) {
        params.imageAddress = JSON.stringify([
          { fileName: '', url: params.imageAddressHome },
        ]);
        if (params.advertisSeat === ADVERTISING_POSITION.FIXED) {
          params.inforMationFlowSeat = '';
        }
      } else {
        params.imageAddress = JSON.stringify([
          { fileName: '', url: params.imageAddressHome },
        ]);
        params.advertisSeat = '';
        params.inforMationFlowSeat = '';
        if (params.advertisSeat === ADVERTISING_POSITION.FIXED) {
          params.inforMationFlowSeat = '';
        }
      }
      let tempArr = [];
      tempArr = await Promise.all(
        JSON.parse(params.imageAddress).map(async (el) => {
          if (el.url.indexOf('.mp4') > -1) {
            return {
              fileName: el.fileName,
              url: el.url,
            };
          } else {
            const tempObj = await this.getImgWidthHeight(el.url);
            return {
              fileName: el.fileName,
              url: el.url,
              ...tempObj,
            };
          }
        })
      );
      //app
      params.appParams =
        this.appParams.length > 0 ? this.appParams : this.form.appParams;
      //小程序
      params.mpParams =
        this.mpParams.length > 0 ? this.mpParams : this.form.mpParams;

      if (params.advertisType !== '1') {
        params.countdownTime = '';
      }
      params.imageAddress = JSON.stringify(tempArr);
      if (this.form) {
        params.advertisLinkType = this.form.advertisLinkType;
        params.advertisPageId =
          this.form.advertisPageId === '' ||
          this.form.advertisPageId === undefined ||
          this.form.advertisPageId === null
            ? ''
            : Number(this.form.advertisPageId);
        params.thirdLinkFlag = this.form.thirdLinkFlag
          ? this.form.thirdLinkFlag
          : '1';

        //跳转的时候
        params.advertisLink = this.form.advertisLink;
        if (this.form.jumpFlag === '0') {
          this.form.advertisLink = '';
          if (this.form.advertisLinkType === '0') {
            params.advertisLink = '';
            params.thirdLinkFlag = '1';
          } else {
            params.advertisPageId = '';
            params.appParams = '[]';
            params.mpParams = '[]';
          }
          // 跳转
          params.advertisLinkType = this.form.advertisLinkType || '0';
        } else {
          params.advertisLinkType = '';
          params.advertisLink = '';
          params.thirdLinkFlag = '1';
          params.advertisPageId = '';
          params.appParams = '[]';
          params.mpParams = '[]';
        }
      }
      if (params.appAdvertisLink) {
        delete params.appAdvertisLink;
      }
      if (params.mpAdvertisLink) {
        delete params.mpAdvertisLink;
      }
      return params;
    },
    check(type) {
      if (type === 'add') {
        if (this.count === 0 && this.form.jumpFlag === '0') {
          return false;
        }
      }
      const advertisLinkType = this.form.advertisLinkType || '';
      const advertisPageId = this.form.advertisPageId || '';
      const advertisLink = this.form.advertisLink || '';
      if (
        this.form.jumpFlag === '0' &&
        (!advertisLinkType ||
          (advertisLinkType === '0' && !advertisPageId) ||
          (advertisLinkType === '1' && !advertisLink))
      ) {
        return false;
      }
      return true;
    },
    // 编辑
    async handleUpdate(row, index, done, loading) {
      const flag = this.check();
      if (!flag) {
        this.$message.warning('请填写选择链接里的内容');
        loading();
        return;
      }
      try {
        const params = await this.getParams(row);
        const res = await putObj(params);
        if (res && res.data && res.data.code === 0) {
          this.form.advertisLinkType = '';
          this.form.advertisPageId = '';
          this.form.appParams = '[]';
          this.form.mpParams = '[]';
          this.form.advertisLink = '';
          this.form.thirdLinkFlag = '';
        }
        done();
        this.$message.success('操作成功');
        this.getList(this.page, true);
      } catch (error) {
        loading();
        throw new Error(error);
      }
    },
    // 保存
    async handleSave(row, done, loading) {
      const flag = this.check('add');
      if (!flag) {
        this.$message.warning('请填写选择链接里的内容');
        loading();
        return;
      }
      const params = await this.getParams(row);
      try {
        await addObj(params);
        done();
        this.$message.success('操作成功');
        this.getList(this.page, true);
      } catch (error) {
        this.form.advertisLink = params.advertisLink;
        loading();
        throw new Error(error);
      }
    },
    // 列表查询
    getList(page, refresh) {
      if (refresh) {
        this.page.current = 1;
        this.page.currentPage = 1;
      }
      this.tableLoading = true;
      const timeObj = {};
      if (
        this.searchForm.advertisingTime &&
        this.searchForm.advertisingTime.length
      ) {
        timeObj.advertisStartDate = this.searchForm.advertisingTime[0];
        timeObj.advertisEndDate = this.searchForm.advertisingTime[1];
        // delete this.searchForm.advertisingTime;
      }
      debugger;
      fetchList(
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize,
          },
          this.searchForm,
          timeObj
        )
      )
        .then((response) => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          this.tableData.forEach((el) => {
            el.advertisingTime = `${el.advertisStartDate}到${el.advertisEndDate}`;
          });
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    beforeClose(done) {
      // this.form.advertisLinkType = '0';
      // this.form.advertisPageId = '';
      // this.form.thirdLinkFlag = '';
      // this.form.advertisLink = '';
      done();
    },
    // 打开窗口前的拦截，调用详情接口回显数据
    async beforeOpen(done, btnType) {
      this.btnType = btnType;
      // 如果不是新增
      if (btnType !== 'add') {
        const { data } = await getObj(this.form.id);
        this.form = data.data;
        // this.choseLinkObject = this.form;
        this.form.advertisingFormTime = [
          this.form.advertisStartDate,
          this.form.advertisEndDate,
        ];
        this.form.advertisingTime = `${this.form.advertisStartDate}到${this.form.advertisEndDate}`;
        if (this.form.advertisType === ADVERTISING_TYPE.GUIDE) {
          this.form.imageAddressGuide = JSON.parse(this.form.imageAddress).map(
            (el) => el.url
          )[0];
        } else {
          this.form.imageAddressHome = JSON.parse(this.form.imageAddress).map(
            (el) => el.url
          );
        }
      } else {
        this.form.advertisLinkType = '0';
        this.form.thirdLinkFlag = '';
        this.form.advertisLink = '';
        this.form.advertisPageId = '';
        this.count = 0;
      }
      done();
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile('/app/appuser/export', this.searchForm, 'appuser.xlsx');
    },
  },
};
</script>
